// server
const datagram = require("dgram");
const searcher = datagram.createSocket("udp4");
const sender = datagram.createSocket("udp4");

const getIpAddress = require("../ip");
const { updateDevices } = require('./devices');

const ip = getIpAddress();
const port = Math.round(Math.random() * (19999 - 15000 + 1) + 15000)
console.log("ip=", ip, 'port', port);

const targetPost = 14099
// const targetPost = 15488
function upd() {
  return new Promise((resolve, reject) => {

    searcher.on('error', e => {
      console.log('error e=', e)
      searcher.close()
      sender.close()
      reject()
    })

    const devices = []
    searcher.on('message', async msg => {
      const text = msg.toString()
      const newSearchDevice = JSON.parse(text)
      console.log('message=', text)
      if (devices.every(device => newSearchDevice.ip && device.ip != newSearchDevice.ip)) {
        devices.push(newSearchDevice)
        updateDevices(devices, ip, port).then(() =>{
          searcher.close()
          sender.close()
          resolve()
        }).catch(() => {
          searcher.close()
          sender.close()
          reject()
        })
      }
    })

    searcher.bind(port, ip)

    sender.bind(0, ip, () => sender.setBroadcast(true))
    SocketSend()

    function SocketSend() {
      setTimeout(() => {
        sendMsg()
      }, 2);
    }

    function sendMsg() {
      sender.send(`{"ip": "${ip}", "port": "${port}"}`, targetPost, '255.255.255.255', e => {
        console.log('sender.send e=', e)
        if (e) {
          searcher.close()
          sender.close()
          reject()
        }

        // setTimeout(() => {
        //   searcher.close()
        //   sender.close()
        //   console.log('搜索设备超时了')
        // }, 30000);
      })
    }
  })
}

module.exports = upd